package com.gw.booking.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class WXAppletUserInfo {

    static Logger logger = LoggerFactory.getLogger(WXAppletUserInfo.class);
    /**
     * 获取微信小程序 session_key 和 openid
     *
     * @param code 调用微信登陆返回的Code
     * @return
     * @author zhy
     */
//    public static JSONObject getSessionKeyOropenid(String code) {
//        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
//        Map<String, String> requestUrlParam = new HashMap<String, String>();
//        requestUrlParam.put("appid", appid);  //开发者设置中的appId
//        requestUrlParam.put("secret", appSecret); //开发者设置中的appSecret
//        requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code
//        requestUrlParam.put("grant_type", "authorization_code");    //默认参数
//        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, requestUrlParam));
//        System.out.println(jsonObject.toString());
//        return jsonObject;
//    }
    public static JSONObject getSessionKeyOropenidForMerchant(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";  //请求地址 https://api.weixin.qq.com/sns/oauth2/access_token
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", Constant.MERCHANT_APPID);  //开发者设置中的appId
        requestUrlParam.put("secret", Constant.MERCHANT_APPSECRET); //开发者设置中的appSecret
        requestUrlParam.put("code", code); //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, requestUrlParam));
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject getAccessTokenForMerchant() {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token";  //请求地址 https://api.weixin.qq.com/sns/oauth2/access_token
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", Constant.MERCHANT_APPID);  //开发者设置中的appId
        requestUrlParam.put("secret", Constant.MERCHANT_APPSECRET); //开发者设置中的appSecret
        requestUrlParam.put("grant_type", "client_credential"); //默认参数
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, requestUrlParam));
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject getIdentificationForMerchant(String accessToken, String openId) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendHttprequest(requestUrl));
        System.out.println(jsonObject.toString());
        if (jsonObject.get("subscribe") == null||jsonObject.get("subscribe").equals("0")) {
            throw new ApiException(MessageCode.CODE_MERCHANT_NEED_BINDED);
        }
        return jsonObject;
    }

    public static JSONObject sendSmsForMerchant(String openId, String accessToken, String orderDate, String phone
            , String msg, String url, String name) {
        String requestUrl = Constant.ORDER_MERCHANT_URL + accessToken;
        JSONObject jsonObjectNews = new JSONObject();
        jsonObjectNews.put("touser", openId);
        jsonObjectNews.put("template_id", Constant.ORDER_ADD_MODEL_ID);
        jsonObjectNews.put("topcolor", "#FF0000");
        jsonObjectNews.put("url", url);
        JSONObject jsonObjectNew = new JSONObject();
        JSONObject jsonObjectNew1 = new JSONObject();
        jsonObjectNew1.put("value", Constant.ORDER_ADD_MODEL_MSG_1);
        jsonObjectNew1.put("color", "#173177");
        JSONObject jsonObjectNew2 = new JSONObject();
        jsonObjectNew2.put("value", name);
        jsonObjectNew2.put("color", "#173177");
        JSONObject jsonObjectNew3 = new JSONObject();
        jsonObjectNew3.put("value", phone);
        jsonObjectNew3.put("color", "#173177");
        JSONObject jsonObjectNew4 = new JSONObject();
        jsonObjectNew4.put("value", orderDate);
        jsonObjectNew4.put("color", "#173177");
        JSONObject jsonObjectNew5 = new JSONObject();
        jsonObjectNew5.put("value", msg);
        jsonObjectNew5.put("color", "#173177");
        JSONObject jsonObjectNew6 = new JSONObject();
        jsonObjectNew6.put("value", Constant.ORDER_ADD_MODEL_MSG_2);
        jsonObjectNew6.put("color", "#173177");
        System.out.println(jsonObjectNew1.toString() + jsonObjectNew2.toString() + jsonObjectNew3.toString() + jsonObjectNew4.toString() + jsonObjectNew5.toString());
        jsonObjectNew.put("first", jsonObjectNew1);
        jsonObjectNew.put("keyword1", jsonObjectNew2);
        jsonObjectNew.put("keyword2", jsonObjectNew3);
        jsonObjectNew.put("keyword3", jsonObjectNew4);
        jsonObjectNew.put("keyword4", jsonObjectNew5);
        jsonObjectNew.put("remark", jsonObjectNew6);
        jsonObjectNews.put("data", jsonObjectNew);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, jsonObjectNews.toJSONString()));
        System.out.println(jsonObject.toString());
        logger.info(requestUrl);
        logger.info(jsonObjectNews.toJSONString());
        logger.info(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject sendSmsForMerchantChange(String openId, String accessToken, String orderDate, String phone
            , String msg, String url, String name) {
        String requestUrl = Constant.ORDER_MERCHANT_URL + accessToken;
        JSONObject jsonObjectNews = new JSONObject();
        jsonObjectNews.put("touser", openId);
        jsonObjectNews.put("template_id", Constant.ORDER_ADD_MODEL_ID);
        jsonObjectNews.put("topcolor", "#FF0000");
        jsonObjectNews.put("url", url);
        JSONObject jsonObjectNew = new JSONObject();
        JSONObject jsonObjectNew1 = new JSONObject();
        jsonObjectNew1.put("value", Constant.ORDER_UPDATE_MODEL_MSG_1);
        jsonObjectNew1.put("color", "#173177");
        JSONObject jsonObjectNew2 = new JSONObject();
        jsonObjectNew2.put("value", name);
        jsonObjectNew2.put("color", "#173177");
        JSONObject jsonObjectNew3 = new JSONObject();
        jsonObjectNew3.put("value", phone);
        jsonObjectNew3.put("color", "#173177");
        JSONObject jsonObjectNew4 = new JSONObject();
        jsonObjectNew4.put("value", orderDate);
        jsonObjectNew4.put("color", "#173177");
        JSONObject jsonObjectNew5 = new JSONObject();
        jsonObjectNew5.put("value", msg);
        jsonObjectNew5.put("color", "#173177");
        JSONObject jsonObjectNew6 = new JSONObject();
        jsonObjectNew6.put("value", Constant.ORDER_UPDATE_MODEL_MSG_2);
        jsonObjectNew6.put("color", "#173177");
        System.out.println(jsonObjectNew1.toString() + jsonObjectNew2.toString() + jsonObjectNew3.toString() + jsonObjectNew4.toString() + jsonObjectNew5.toString());
        jsonObjectNew.put("first", jsonObjectNew1);
        jsonObjectNew.put("keyword1", jsonObjectNew2);
        jsonObjectNew.put("keyword2", jsonObjectNew3);
        jsonObjectNew.put("keyword3", jsonObjectNew4);
        jsonObjectNew.put("keyword4", jsonObjectNew5);
        jsonObjectNew.put("remark", jsonObjectNew6);
        jsonObjectNews.put("data", jsonObjectNew);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, jsonObjectNews.toJSONString()));
        System.out.println(jsonObject.toString());
        logger.info(requestUrl);
        logger.info(jsonObjectNews.toJSONString());
        logger.info(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject getUserInfoForMerchant(String openId, String accessToken) {
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        System.out.println(requestUrl);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendHttprequest(requestUrl));
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject getSessionKeyOropenidForDiner(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", Constant.DINER_APPID);  //开发者设置中的appId
        requestUrlParam.put("secret", Constant.DINER_APPSECRET); //开发者设置中的appSecret
        requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, requestUrlParam));
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject getAccessTokenForDiner() {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token";  //请求地址 https://api.weixin.qq.com/sns/oauth2/access_token
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", Constant.DINER_APPID);  //开发者设置中的appId
        requestUrlParam.put("secret", Constant.DINER_APPSECRET); //开发者设置中的appSecret
        requestUrlParam.put("grant_type", "client_credential"); //默认参数
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, requestUrlParam));
        System.out.println(jsonObject.toString());
        return jsonObject;
    }

    public static void sendSmsForDiner(String openId, String accessToken, String templateId, String formId, String url
            , String shopName, String orderDate, String address, String msg) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + accessToken;
        JSONObject jsonObjectNews = new JSONObject();
        jsonObjectNews.put("touser", openId);
        jsonObjectNews.put("template_id", templateId);
        jsonObjectNews.put("form_id", formId);
        jsonObjectNews.put("page", url);
        JSONObject jsonObjectNew = new JSONObject();
        JSONObject jsonObjectNew1 = new JSONObject();
        jsonObjectNew1.put("value", shopName);
        jsonObjectNew1.put("color", "#173177");
        JSONObject jsonObjectNew2 = new JSONObject();
        jsonObjectNew2.put("value", orderDate);
        jsonObjectNew2.put("color", "#173177");
        JSONObject jsonObjectNew3 = new JSONObject();
        jsonObjectNew3.put("value", address);
        jsonObjectNew3.put("color", "#173177");
        jsonObjectNew.put("keyword1", jsonObjectNew1);
        jsonObjectNew.put("keyword2", jsonObjectNew2);
        jsonObjectNew.put("keyword3", jsonObjectNew3);
        if (msg != null) {
            JSONObject jsonObjectNew4 = new JSONObject();
            jsonObjectNew4.put("value", msg);
            jsonObjectNew4.put("color", "#173177");
            jsonObjectNew.put("keyword4", jsonObjectNew4);
        }
        jsonObjectNews.put("data", jsonObjectNew);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, jsonObjectNews.toJSONString()));
        System.out.println(jsonObject.toString());
        logger.info(requestUrl);
        logger.info(jsonObjectNews.toJSONString());
        logger.info(jsonObject.toString());
    }

    public static void sendSmsForDinerChange(String openId, String accessToken, String templateId, String formId, String url
            , String orderDetail, String orderDetailNew, String msg) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + accessToken;
        JSONObject jsonObjectNews = new JSONObject();
        jsonObjectNews.put("touser", openId);
        jsonObjectNews.put("template_id", templateId);
        jsonObjectNews.put("form_id", formId);
        jsonObjectNews.put("page", url);
        JSONObject jsonObjectNew = new JSONObject();
        JSONObject jsonObjectNew1 = new JSONObject();
        jsonObjectNew1.put("value", orderDetail);
        jsonObjectNew1.put("color", "#173177");
        JSONObject jsonObjectNew2 = new JSONObject();
        jsonObjectNew2.put("value", orderDetailNew);
        jsonObjectNew2.put("color", "#173177");
        JSONObject jsonObjectNew3 = new JSONObject();
        jsonObjectNew3.put("value", msg);
        jsonObjectNew3.put("color", "#173177");
        jsonObjectNew.put("keyword1", jsonObjectNew1);
        jsonObjectNew.put("keyword2", jsonObjectNew2);
        jsonObjectNew.put("keyword3", jsonObjectNew3);
        jsonObjectNews.put("data", jsonObjectNew);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, jsonObjectNews.toJSONString()));
        System.out.println(jsonObject.toString());
        logger.info(requestUrl);
        logger.info(jsonObjectNews.toJSONString());
        logger.info(jsonObject.toString());
    }

    public static void sendSmsForDinner(String openId, String accessToken, String templateId, String url, String name
            , String orderDate, String shopName, String orderMsg){
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        JSONObject jsonObjectNews = new JSONObject();
        jsonObjectNews.put("touser", openId);
        jsonObjectNews.put("template_id", templateId);
        jsonObjectNews.put("page", url);
        JSONObject jsonObjectNew = new JSONObject();
        JSONObject jsonObjectNew1 = new JSONObject();
        jsonObjectNew1.put("value",name);
        JSONObject jsonObjectNew2 = new JSONObject();
        jsonObjectNew2.put("value", orderDate);
        JSONObject jsonObjectNew3 = new JSONObject();
        jsonObjectNew3.put("value", shopName);
        JSONObject jsonObjectNew4 = new JSONObject();
        jsonObjectNew4.put("value", orderMsg);
        jsonObjectNew.put("thing1", jsonObjectNew1);
        jsonObjectNew.put("time2", jsonObjectNew2);
        jsonObjectNew.put("thing3", jsonObjectNew3);
        jsonObjectNew.put("thing5", jsonObjectNew4);
        jsonObjectNews.put("data", jsonObjectNew);
        JSONObject jsonObject = JSON.parseObject(HttpRequestUtil.sendPost(requestUrl, jsonObjectNews.toJSONString()));
        System.out.println(jsonObject.toString());
        logger.info(requestUrl);
        logger.info(jsonObjectNews.toJSONString());
        logger.info(jsonObject.toString());
    }

    //
    // 商家端
    //wxfaaa4af41d451ca0
    //783a7be1a8530fe94c42f85d7927cab7
    //用户端
    //wxdb0a3ed59bdab464
    //734b878877ab0228a5011a43fac2a253
//    private static final String appid = "wx4b5dc95166682c2c";
//    private static final String appSecret = "c4f1a8960524de0194a31d140d1ac2cc";
//    private static final String urlGetAccessTokenByCode
//            = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={SECRET}&code={CODE}&grant_type=authorization_code";

//    public static String getOpenIdByCode(String code) {
//        String url = urlGetAccessTokenByCode.replace("{APPID}", appid)
//                .replace("{SECRET}", appSecret)
//                .replace("{CODE}", code);
//        try {
//            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(IOUtils.toString(new URL(url).openStream()));
//            return json.toString();
//        } catch (Exception e) {
//            return null;
//        }
//    }


    /**
     //     * 解密用户敏感数据获取用户信息
     //     *
     //     * @param sessionKey    数据进行加密签名的密钥
     //     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     //     * @param iv            加密算法的初始向量
     //     * @return
     //     * @author zhy
     //     */
//    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) throws Exception {
//        // 被加密的数据
//        BASE64Decoder decoder = new BASE64Decoder();
//        byte[] dataByte = decoder.decodeBuffer(encryptedData);
//        // 加密秘钥
//        byte[] keyByte = decoder.decodeBuffer(sessionKey);
//        // 偏移量
//        byte[] ivByte = decoder.decodeBuffer(iv);
//
//        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
//        int base = 16;
//        if (keyByte.length % base != 0) {
//            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
//            byte[] temp = new byte[groups * base];
//            Arrays.fill(temp, (byte) 0);
//            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
//            keyByte = temp;
//        }
//        // 初始化
//        Security.addProvider(new BouncyCastleProvider());
//        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
//        parameters.init(new IvParameterSpec(ivByte));
//        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//        byte[] resultByte = cipher.doFinal(dataByte);
//        if (null != resultByte && resultByte.length > 0) {
//            String result = new String(resultByte, "UTF-8");
//            return JSON.parseObject(result);
//        }
//        return null;
//    }


}
